﻿using AnQinFrameWorkAPI.DataBase;
using AnQinFrameWorkAPI.Entity.Blog.DTO.BlogDevelopHistory;
using AnQinFrameWorkAPI.Entity.Blog.Entity;
using AnQinFrameWorkAPI.Entity.Blog.View.BlogDevelopHistory;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using FrameWork.DataHelper;
using FrameWork.Entity;
using FrameWork.Request;
using Microsoft.EntityFrameworkCore;

namespace AnQinFrameWorkAPI.Service.Blog;

/// <summary>
///     博客发展历程服务
/// </summary>
public class BlogDevelopHistoryService
{
    private readonly DatabaseContext _context;
    private readonly IMapper _mapper;

    /// <summary>
    ///     构造函数（依赖注入）
    /// </summary>
    public BlogDevelopHistoryService(DatabaseContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    #region 获取发展历程列表（分页）

    public async Task<RequestResponseModel> GetBlogDevelopHistoryList(BlogDevelopHistorySearchDTO searchDTO)
    {
        // 构建基础查询
        var query = _context.BlogDevelopHistory
            .ProjectTo<BlogDevelopHistoryView>(_mapper.ConfigurationProvider)
            .AsNoTracking()
            .WhereIF(a => a.Code.Contains(searchDTO.Code), !string.IsNullOrEmpty(searchDTO.Code))
            .WhereIF(a => a.Name.Contains(searchDTO.Name), !string.IsNullOrEmpty(searchDTO.Name))
            .WhereIF(a => a.Title.Contains(searchDTO.Title), !string.IsNullOrEmpty(searchDTO.Title))
            .WhereIF(a => a.Introduce.Contains(searchDTO.Introduce), !string.IsNullOrEmpty(searchDTO.Introduce))
            .WhereIF(a => a.CreateTime > searchDTO.StartTime, searchDTO.StartTime != null)
            .WhereIF(a => a.CreateTime < searchDTO.EndTime, searchDTO.EndTime != null);

        // 获取分页数据（Page是框架提供的分页方法）
        var histories = await query
            .OrderByDescending(a => a.CreateTime)
            .Page(searchDTO.PageIndex, searchDTO.PageSize)
            .ToListAsync();

        // 获取总数
        var totalCount = await query.CountAsync();

        return RequestResponse.OK(new PageResult<BlogDevelopHistoryView>(histories, totalCount), "查询成功");
    }

    #endregion

    #region 新增发展历程

    public async Task<RequestResponseModel> AddBlogDevelopHistory(BlogDevelopHistoryAddDTO addDTO)
    {
        // 映射到实体模型
        var history = _mapper.Map<BlogDevelopHistoryModel>(addDTO);

        // 设置默认值（框架规范）
        history.Id = Guid.NewGuid();
        history.CreateTime = DateTime.Now;

        // 添加到数据库
        _context.BlogDevelopHistory.Add(history);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(history.Id, "新增成功");
    }

    #endregion

    #region 更新发展历程

    public async Task<RequestResponseModel> PutBlogDevelopHistory(BlogDevelopHistoryUpdateDTO updateDTO)
    {
        // 使用框架提供的Valid方法验证ID有效性
        var existing = await Valid.ValidId(_context.BlogDevelopHistory, updateDTO.Id);
        if (existing == null) return RequestResponse.ErrorRequest("发展历程ID无效");

        // 更新实体数据（框架规范）
        _mapper.Map(updateDTO, existing);

        // 保存到数据库
        _context.BlogDevelopHistory.Update(existing);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(updateDTO.Id, "更新成功");
    }

    #endregion

    #region 删除发展历程

    public async Task<RequestResponseModel> DeleteBlogDevelopHistory(SingleIdDTO deleteDTO)
    {
        // 使用框架提供的Valid方法验证ID有效性
        var history = await Valid.ValidId(_context.BlogDevelopHistory, deleteDTO.Id);
        if (history == null) return RequestResponse.ErrorRequest("发展历程ID无效");

        // 执行删除（框架规范）
        _context.BlogDevelopHistory.Remove(history);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(deleteDTO.Id, "删除成功");
    }

    #endregion
}